<?php
namespace app\admin\controller;

use app\common\model\Message;
use think\Db;
use think\Request;
use think\Validate;

class BabyGrowLog extends Common
{

    /**
     * 列表
     */
    public function index(){
        $baby_id = input('baby_id');
        $baby = \app\common\model\Baby::get($baby_id);
        if(empty($baby)){
            return ['code'=>'1','msg'=>'宝宝信息不存在'];
        }
        $parent = \app\common\model\Parents::get($baby['parent_id']);
        if(empty($baby)){
            return ['code'=>'1','msg'=>'家长信息不存在'];
        }
        if(Request::instance()->isAjax()){
            $input = array_filter(input('','','trim'));
            return \app\common\model\BabyGrowLog::getList($input);
        }
        return view('',['baby_id'=>$baby_id,'baby'=>$baby,'parent'=>$parent]);
    }

    /**
     * 删除
     */
    public function delete(){
        try{
            $id = input('id');
            $role = \app\common\model\BabyGrowLog::where(['id'=>$id])->delete();
            if ($role){
                return ['code'=>'0','msg'=>'删除成功'];
            }else{
                return ['code'=>'1','msg'=>'删除失败'];
            }
        }catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
    }

    /**
     * 创建
     */
    public function create(){
        $this->view->engine->layout('common/iframe');
        $baby_id = input('baby_id');
        $baby = \app\common\model\Baby::get($baby_id);
        return view('',['baby'=>$baby]);
    }

    /**
     * 保存
     */
    public function save(){
        try{
            $data = input('post.','','trim');
            $baby = \app\common\model\Baby::get($data['baby_id']);
            $data['parent_id'] = $baby['parent_id'];
            if(empty($data['before_height'])){
                unset($data['before_measure_time']);
            }
            Db::startTrans();
//            if(isset($data['id']) && !empty($data['id'])){
//                $role = \app\common\model\Article::get(['id'=>$data['id']]);
//                if($role->allowField(true)->force()->update($data) === false){
//                    exception('保存失败');
//                }
//            }else{
                $role = new \app\common\model\BabyGrowLog($data);
                if(!$role->allowField(true)->force()->save($data)){
                    exception('保存失败');
                }
//            }
            Db::commit();
            return  json(['code'=>0,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }

    }


}
